package com.bw.gateway.filters;

import com.bw.common.constants.TokenConstants;
import com.bw.common.utils.JwtUtils;
import com.bw.common.utils.StringUtils;
import com.bw.gateway.config.IgnoreWhitesConfig;
import com.bw.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName:
 * @Description: 鉴权过滤过滤器     验证 token
 * @Author: zhuwenqiang
 * @Date: 2024/10/18
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreWhitesConfig ignoreWhitesConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 过滤方法
     * @param exchange  ServerWebExchange 请求的上下文对象  使用它来获取请求和响应对象
     * @param chain     GatewayFilterChain  网关过滤器链    放行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 判断当前请求是否需要拦截   白名单
        // 获取加载的白名单请求
        List<String> whites = ignoreWhitesConfig.getWhites();  // /auth/sendCode/**
        // 判断当前的请求是否是白名单的请求
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (StringUtils.matches(path, whites)) {  // 发送短信验证码  /auth/sendCode/13812121212
            // 白名单请求 放行
            return chain.filter(exchange);
        }
        // 验证 token
        // 获取 token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        // 非空验证
        if (StringUtils.isBlank(token)) {
            return GatewayUtils.errorResponse(exchange, "token 不能为空");
        }
        // 合法性验证
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange, "token 不合法");
        }
        // 有效性验证
        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) {
            return GatewayUtils.errorResponse(exchange, "token 过期");
        } else {
            // 续期
            redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey, 30, TimeUnit.MINUTES);
        }
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 指定 过滤器执行顺序的
     * @return  数字  数字越小 优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }

}
